package com.rrkd.handler;

import java.io.File;

import com.rrkd.model.RequestFile;
import com.rrkd.model.ResponseFile;
import com.rrkd.util.FileTransferProperties;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class FileTransferByPointHandler extends ChannelInboundHandlerAdapter {

	private long filesize = 0l;
	/**
	 * 文件默认存储地址
	 */
	private static String file_dir = FileTransferProperties.getString(
			"file_write_path", "/");

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		if (msg instanceof RequestFile) {

			RequestFile request = (RequestFile) msg;
			// 断点续传
			if (request.getUpload_status() != null
					&& request.getUpload_status().equals("point")&&request.getRemotefile_size()==0) {
				filesize = getFileSize(request);// 服务端文件大小

				if (filesize == 0) {
					return;
				} else if (!request.getFile_type().equals("emptDir")
						&& filesize <= request.getLocalfile_size()) {//判断为非空文件夹并且远程文件的大小于客户端的文件大小
					request.setRemotefile_size(filesize);
					ctx.writeAndFlush(request);
				}
			}else {
				ctx.fireChannelRead(request);
			}

		}

	}

	public long getFileSize(RequestFile ef) {

		String filedir = ef.getUploadDestPath()+File.separator+ef.getFile_name()+ef.getFile_type();
		File localFile = new File(filedir);

		if (localFile.exists()) {
			filesize = localFile.length();
			System.out.println(filesize);
		} else {

			System.out.println("此文件在服务端不存在,不需要进行断点续传");

		}
		return filesize;

	}
}
